source ./config.sh
source ./logging.sh

# Usage: create_temp <prefab path> <tempfile path> <checktag>
create_temp() {
	# get all positions and their files.
	cat -n $1 | sed -n "/\\[$3/p" | sed "s/$3//" | tr -d ' \t]' | tr '[' ' ' > $2
	#log "extracted $(tail -1 $2) from $1"
}

# Usage: glue <prefab path> <index path> <tempfile> <checktag>
glue() {
	# now insert their content.
	cp $1 $2 2> /dev/null
	while IFS= read -r line; do
		line=$(echo "$line" | cut -f2 -d" ")
		sed "/$4 "$(echo $line | sed 's/\./\\./g; s/\//\\\//g')'/q' $2 | head -n -1 > $2.tmp
		echo $line
		if [ -f $RESOURCE_PATH/$4/$line ]; then
			if [ $4 == 'IMG' ]; then
				echo "<img src=\"$line\">" >> $2.tmp
#				if ! [ -d "$(dirname $2)/resource" ]; then
#					mkdir "$(dirname $2)/resource"
#				fi
				cp $RESOURCE_PATH/$4/$line $HTML_DIRECTORY/$line

				sed -i "s/#000/$BACKGROUND_COLOR/" $HTML_DIRECTORY/$line
				#ln -s  $RESOURCE_PATH/$4/$line $HTML_DIRECTORY/$line
			else
				cat $RESOURCE_PATH/$4/$line >> $2.tmp
			fi
		else
			echo "" \
			"<div class=\"w3-panel w3-red\">" \
			"<p>! MISSING FILE:" \
			"$line [$3]!</p>" \
			"</div>" >> $2.tmp
		fi
		sed -n "/$4 "$(echo $line | sed 's/\./\\./g; s/\//\\\//g')'/,$p' $1 | tail -n +2 >> $2.tmp
		mv $2.tmp $2
	done < $3
}
